export default function applyMiddleware(...middlewares) {
  return (createStore) => (reducer, preloadedState, enhancer) => {
    const store = createStore(reducer, preloadedState, enhancer)
    let dispatch = store.dispatch
    let chain = []

    //暴露给中间件的API，所以redux-thunk可以使用形如return (dispatch, getState)=>{}
    const middlewareAPI = {
      getState: store.getState,
      dispatch: (action) => dispatch(action)
    }
    //将暴露的API给中间件，调用中间件函数，生成中间件返回值函数（为什么返回值是函数？不是函数下面的compose()就报错了）
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    //组合全部中间件的返回值函数， chain是中间件返回值函数们
    //然后reduce起来的函数返回的也是函数，将store原来的dispatch传进去，dispatch函数也是接受一个action并返回一个action，作为中间件链的头部
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}


//compose(funcA, funcB, funcC) 等于 (args)=>funcA(funcB(funcC(args)))
export default function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}